package icu.which.strongchild.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import icu.which.strongchild.common.BaseResponse;
import icu.which.strongchild.common.ErrorCode;
import icu.which.strongchild.common.ResultUtils;
import icu.which.strongchild.exception.BusinessException;
import icu.which.strongchild.model.domain.User;
import icu.which.strongchild.model.vo.UserVO;
import icu.which.strongchild.request.UserRegisterRequest;
import icu.which.strongchild.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 注册
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/userRegister")
    public BaseResponse<Boolean> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        //空
        if(userRegisterRequest == null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        //空
        String userAccount = userRegisterRequest.getUserAccount();
        String password = userRegisterRequest.getPassword();
        if(StringUtils.isAnyBlank(userAccount, password)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        boolean res = this.userService.register(userAccount,password);
        return ResultUtils.success(new Boolean(res));
    }

    /**
     * 登录
     * @param userRegisterRequest
     * @param request
     * @return
     */
    @PostMapping("/userLogin")
    public BaseResponse<UserVO> userLogin(@RequestBody UserRegisterRequest userRegisterRequest, HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO user = this.userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 登出
     * @param request
     * @return
     */
    @PostMapping("/userLogout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        boolean logout = this.userService.logout(request);
        return ResultUtils.success(logout);
    }

    /**
     * 已登录的用户
     * @param request
     * @return
     */
    @PostMapping("/currentUser")
    public BaseResponse currentUser(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        UserVO loginUser = this.userService.getLoginUser(request);
        return ResultUtils.success(loginUser);
    }

    /**
     * 更新用户
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/updateUser")
    public BaseResponse updateUser(@RequestBody User user,HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if(user == null||user.getId()<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = this.userService.updateUser(user, request);
        if(b){
            return ResultUtils.success(true);
        }else {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"操作失败");
        }
    }

    /**
     * 删除用户
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/deleteUser")
    public BaseResponse deleteUser(@RequestBody User user,HttpServletRequest request) {
        if (user == null||request == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if(user.getId()<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = this.userService.deleteUser(user.getId(), request);
        if(b){
            return ResultUtils.success(true);
        }else {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"操作失败");
        }
    }

    /**
     * 根据标签查询
     * @param
     * @return
     */
    @GetMapping("/searchUserBytags")
    public BaseResponse<List<UserVO>> searchUserBytags(@RequestParam(required = false) List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<UserVO> res = userService.searchUsersByTags(tagNameList);
        return ResultUtils.success(res);
    }

    /**
     * 获取最匹配的用户
     *
     * @param num 数量
     * @param request session
     * @return
     */
    @GetMapping("/match")
    public BaseResponse matchUsers(long num, HttpServletRequest request) {
        if (num <= 0 || num > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        return ResultUtils.success(userService.recommondUserByTags(num, request));
    }

    /**
     *  展示用户
     * @param pageSize 页面大小
     * @param pageNum 第几页
     * @param request session
     * @return
     */
    @GetMapping("/recommend")
    public BaseResponse<Page<User>> recommendUsers(long pageSize, long pageNum, HttpServletRequest request) {
        UserVO loginUser = userService.getLoginUser(request);
        String redisKey = String.format("child:user:recommend:%s", loginUser.getId());
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // 如果有缓存，直接读缓存
        Page<User> userPage = (Page<User>) valueOperations.get(redisKey);
        if (userPage != null) {
            log.info("有缓存！！！！！！！！！！！！！！！！！！");
            return ResultUtils.success(userPage);
        }

        // 无缓存，查数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        userPage = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        log.info("无缓存+++++++++++++++++++");
        // 写缓存
        try {
            valueOperations.set(redisKey, userPage, 30000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("redis set key error", e);
        }
        return ResultUtils.success(userPage);
    }

}
